package com.siloam.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import com.siloam.dao.GroupDao;
import com.siloam.dao.GroupUserDao;
import com.siloam.module.Group;
import com.siloam.module.GroupUser;
import com.siloam.vo.GroupVO;
import com.siloam.vo.UserVO;

public class GroupService {
	private GroupDao groupDao;
	private GroupUserDao groupUserDao;
	
	public GroupDao getGroupDao() {
		return groupDao;
	}

	public void setGroupDao(GroupDao groupDao) {
		this.groupDao = groupDao;
	}
	
	public GroupUserDao getGroupUserDao() {
		return groupUserDao;
	}

	public void setGroupUserDao(GroupUserDao groupUserDao) {
		this.groupUserDao = groupUserDao;
	}

	public List<GroupVO> findAll(){
		List<Group> groups = groupDao.findAll();
		List<GroupVO> groupVOs = new ArrayList<GroupVO>();
		
		List<GroupUser> gus ;
		for(Group group : groups){
			gus = groupUserDao.listGroupUsers(group.getId());
			group.setGroupUsers(gus);
			
			groupVOs.add(new GroupVO(group) );
		}
		
		return groupVOs;
	}
	
	public List<UserVO> listGroupUser(int groupId){
		List<GroupUser> groupUsers = groupUserDao.listGroupUsers(groupId);
		List<UserVO> userVOs = new ArrayList<UserVO>();
		UserVO userVO;
		for(GroupUser gu : groupUsers){
			userVO = new UserVO(gu.getUser() );
			userVO.setId(gu.getId() );
			userVO.setLeaderOpt(gu);
			userVO.setMemberType(gu.getTypeText());
			userVOs.add(userVO);
		}
		return userVOs;
	}
	
	@Transactional
	public void add(Group group){
		groupDao.add(group);
	}
	
	public Group load(int id){
		return groupDao.load(id); 
	}
	
	@Transactional
	public void update(Group group){
		groupDao.update(group);
	}
	
	@Transactional
	public void setMemberType(int id, int type){
		groupUserDao.setMemberType(id, type); 
	}
	
	@Transactional
	public void delete(String ids){
		groupDao.delete(ids);
	}
	
	public List<Group> findByType(int type){
		return  groupDao.findByType(type);
	}
	
	public void addGroupUsers(String userIds, int groupId){
		String[] ids = userIds.split(",");
		for(String id : ids){
			groupUserDao.add(GroupUser.TYPE_MEMBER, Integer.parseInt(id), groupId);
		}
	}
	
	public void deleteGroupUsers(String ids){
		groupUserDao.delete(ids);
	}
	
}
